import datetime
import time

from django.shortcuts import render
from teacher.models import Teacher
# Create your views here.
from django.http import HttpResponse
import requests
from bs4 import BeautifulSoup



from teacher.utitl import MysqlHelper

mysqlhe=MysqlHelper()

def xiugai(request):
    stu = request.session.get('stu')
    name = request.session.get("name")

    print(name,'$$$$$$$$$$$$$$$')
    teacheruser = Teacher.objects.filter(tname=name).first()
    if teacheruser!=None:
        vb = '信息修改'
        if request.method == 'GET':

            return render(request, 'admin1/gr.html',
                          {'zd':'管理端','vb': vb, 'name': stu, 'zh': teacheruser.tzh, 'tname': teacheruser.tname, 'tpas': "******",
                           'tgender': teacheruser.tgender, 'tid': teacheruser.tid})
        if request.method == 'POST':
            id = request.session.get("id")

            user_name=request.POST['user_name']
            if user_name!='':
                name=user_name
                request.session['name'] = user_name
                Teacher.objects.filter(id=id).update(tname=user_name)
            user_tpas=request.POST['user_tpas']
            if user_tpas!='':
                Teacher.objects.filter(id=id).update(tpas=user_tpas)

            return render(request, 'admin1/gr.html',{'zd':'管理端','vb': vb, 'name': stu, 'zh': teacheruser.tzh, 'tname': teacheruser.tname, 'tpas': "******",
                           'tgender': teacheruser.tgender, 'tid': teacheruser.tid,'jg':'成功'})
        else:
            print("*********************")
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def user(request):
    name = request.session.get("name")

    print(name,'$$$$$$$$$$$$$$$')
    teacheruser = Teacher.objects.filter(tname=name).first()
    if teacheruser!=None:
        vb = '用户列表'
        if request.method == 'GET':
            teacher1=Teacher.objects.all()
            print(type(teacher1))
            return render(request, 'admin1/user.html', {'user': teacher1})

        elif request.method == 'POST':

            return render(request, 'admin1/user.html', {'error': '请登陆'})

        else:
            return render(request, 'teacher/login1.html', {'error': '请登陆'})
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def register2(request):
    stu=request.session.get('stu')
    img = request.FILES.get('tpas')
    imgsql=stu[6]
    zh=stu[2]
    pwd=stu[4]
    if img!=None:
        name1 = request.FILES.get('tpas').name
        print(name1, img.size)
        file_name = './static/img/' + str(int(time.time())) + '.' + name1.split('.')[-1]  # 构造文件名以及文件路径
        urlname = 'static/img/' + str(int(time.time())) + '.' + name1.split('.')[-1]
        if name1.split('.')[-1] not in ['jpeg', 'jpg', 'png', 'gif']:
            return HttpResponse('输入文件有误')
        try:
            with open(file_name, 'wb+') as f:
                f.write(img.read())
        except Exception as e:
            print(e)
        imgsql=urlname
    if 'tname' in request.POST:
        zh = request.POST['tname']

    if 'pwd' in request.POST:
        pwd = request.POST['pwd']


    sql = 'update teachers set 头像="{1}",名字="{2}",密码="{3}" where id={0}'.format(stu[0],imgsql,zh,pwd)
    print(sql)
    mysqlhe.update(sql)
    stu=mysqlhe.get_all('select * from teachers where id={0}'.format(stu[0]))



    return render(request, 'teacher/login1.html')
def user1(request):
    stu = request.session.get("stu")


    if len(stu) != 0:
        vb = '用户列表'
        if request.method == 'GET':
            sql='select * from teachers where 类型 = "0"'


            teacher1=mysqlhe.get_all(sql)
            num=mysqlhe.get_all('select num from num')[0][0]
            print(teacher1)


            return render(request, 'admin1/user1.html', {'vb': vb,'user': teacher1,'name':stu,'num':num})

        elif request.method == 'POST':

            return render(request, 'admin1/user1.html', {'error': '请登陆'})

        else:
            return render(request, 'teacher/login1.html', {'error': '请登陆'})
    else:
        return render(request, 'teacher/login1.html', {'error': '请登陆'})
def qj(request):
    name = request.session.get("name")
    stu = request.session.get("stu")


    teacheruser = Teacher.objects.filter(tname=name).first()
    if teacheruser != None:
        if request.method == 'GET':
            vb = '房屋列表'
            if request.method == 'GET':
                city1 = mysqlhe.get_all('select COUNT(*)as num ,city from teacher_house  group by city ')
                print()
                city = []
                for i in city1:
                    city.append(i[1])
                # city=['1','2','3']
                # house=House.objects.all()
                house = mysqlhe.get_all(
                    'select b.imgurl, b.name, b.hx, b.price, b.mj1, b.xqname, b.id from gj as b ')

                print(house)
                return render(request, 'admin1/qj.html',
                              {'zd': '客户端', 'vb': vb, 'name': stu, 'imgurl': 'static/img/meng.png',
                               'zh': teacheruser.tzh, 'tname': teacheruser.tname, 'tpas': "******",
                               'tgender': teacheruser.tgender, 'tid': teacheruser.tid, 'city': city, 'house': house})
    else:
        return render(request, 'teacher/qj.html', {'error': '请登陆'})
def bk(request):
    stu = request.session.get("stu")
    name = request.session.get("name")
    print(name, '$$$$$$$$$$$$$$$')
    teacheruser = Teacher.objects.filter(tname=name).first()
    if teacheruser != None:
        if request.method == 'GET':
            vb='自动采集'


            return render(request, 'admin1/bk.html', {'vb': vb,'name':stu})
    else:
        return render(request, 'teacher/qj.html', {'error': '请登陆'})
def cj(request):
    url=request.POST['url']
    vb = '数据采集'

    shoyye(url)

    return render(request, 'admin1/bk.html', {'vb': vb})
def ksh(request):
    stu=request.session.get('stu')
    print(stu)
    vb = '可视化'
    zongsql='select count(*) from gj'
    zongnun=mysqlhe.get_all(zongsql)[0][0]
    pjsql="select avg(price) from gj"
    pjnun = mysqlhe.get_all(pjsql)[0][0]

    jinsql= "select count(*) from gj where cear BETWEEN '{0}' and DATE_ADD('{0}',INTERVAL 1 DAY)".format(datetime.datetime.now().strftime('%Y-%m-%d'))

    print(jinsql)
    jinnun = mysqlhe.get_all(jinsql)[0][0]

    lysql='select count(*) from fk'
    lynun = mysqlhe.get_all(lysql)[0][0]
    zheaders=[zongnun,pjnun,jinnun,lynun]

    return render(request, 'admin1/ksh.html', {'vb': vb,'zheaders':zheaders,'name':stu})
def ggfb(request):
    stu = request.session.get('stu')
    if request.method == 'POST':
        name=request.POST['user_name']
        nr = request.POST['nr']
        print(nr)

        addsql='INSERT INTO gg (bt,text) values ("{0}","{1}")'.format(name,nr)
        mysqlhe.insert(addsql)
        return render(request, 'admin1/ggfb.html',{'script':"alert",'wrong':'发布成功'})

    else:
        return render(request, 'admin1/ggfb.html',{'name':stu})
def gglb(request):
    stu = request.session.get('stu')
    cxsql="select * from gg"
    listjg=mysqlhe.get_all(cxsql)
    a=0
    listjson=[]

    for i in listjg:
        listj = []
        a=a+1
        listj.append(a)
        for ii in i:
            listj.append(ii)

        listjson.append(listj)

    return render(request, 'admin1/gglb.html',{'data':listjson,'name':stu})

def lygl(request):
    stu=request.session.get('stu')
    lysql='select * from fk'
    listjg = mysqlhe.get_all(lysql)
    a = 0
    listjson = []

    for i in listjg:
        listj = []
        a = a + 1
        listj.append(a)
        for ii in i:
            listj.append(ii)
        listjson.append(listj)
    return render(request, 'admin1/lygl.html',{'data':listjson,'name':stu})
def lyfk(request):
    stu=request.session.get('stu')
    print('^^^^^^^^^^^^^^^^^')

    if request.method == 'GET':

        print(('id' in request.GET))
        if ('id' in request.GET):
            id=request.GET['id']

            lysql='select * from fk where id={0}'.format(id)
            data=mysqlhe.get_all(lysql)
            print(data)
            return render(request, 'admin1/lyfk.html',{'data':data,'name':stu} )
        else:
            return render(request, 'admin1/lygl.html',{'name':stu} )
        
    else:
        id = request.GET['id']
        nr=request.POST['fk']
        sql='update  fk set hf="{0}" where id={1}'.format(nr,int(id))
        print(sql)
        mysqlhe.update(sql)
        print('121212121')
        lysql='select * from fk where id={0}'.format(id)
        data=mysqlhe.get_all(lysql)
        return render(request, 'admin1/lygl.html',{'data':data,'name':stu})

def xq(xqurl):
    print(xqurl)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/49.0.2623.112 Safari/537.36'}

    html = requests.get(xqurl, headers=headers)
    htmltxt = BeautifulSoup(html.text, "html.parser")
    listdq = (htmltxt.find('div', attrs={'class': 'f-crumbs f-w1190'})).find_all('a')
    onej = listdq[2].text.replace("合租房", "").replace("租房", "")
    twoj = listdq[3].text.replace("合租房", "").replace("租房", "")
    therej = listdq[4].text.replace("合租房", "").replace("租房", "")

    name = htmltxt.find('p', attrs={'class': 'card-title'}).text.replace("\n", "")
    hm = htmltxt.find_all("li", attrs={'class': 'item f-fl'})

    hx = hm[0].find('span', attrs={"class": "content"}).text
    mj = hm[1].find('span', attrs={"class": "content"}).text
    zflx = ''
    if '整租' in mj:
        zflx = '整租'
    elif '合租' in mj:
        zflx = '合租'
    elif '单间' in mj:
        zflx = '单间'
    imgurl = 'http:' + htmltxt.find("div", attrs={'class': 'big-img-wrap'}).find('img').get('src')
    # print(imgurl.replace(" ", ""))
    price = htmltxt.find("span", attrs={"class": 'price'}).text
    mj1 = (mj.split('\xa0\xa0')[1]).replace("㎡", "")
    hm1 = htmltxt.find_all("li", attrs={'class': 'er-item f-fl'})
    if hm1[0].find('a') != None:
        xqname = hm1[0].find('a').text.replace("\n", "")
    else:
        xqname = hm1[0].find('span', attrs={"class": 'content'}).text.replace("\n", "")

    # print(name,price,hx,mj1)
    # print('######################')
    # print('一级区域：',onej)
    # print('二级区域:',twoj)
    # print("三级区域:",therej)
    # print("小区名称:",xqname)
    # print("标题:",name)
    # print("格局：",hx)
    # print("面积：",mj1)
    # print("价格：",price)
    # print("租房模式:",zflx)
    # print("图片:",imgurl)
    mysqlhe = MysqlHelper()
    cxsql = 'select * from gj where xqname="{0}" and name="{1}" and mj1="{2}" '.format(xqname, name, mj1)
    print(cxsql)
    cxlist = mysqlhe.get_all(cxsql)

    if len(cxlist) == 0:
        sql = "INSERT INTO gj (onej,twoj,therej,xqname,name,hx,mj1,price,zflx,imgurl)VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}',{7},'{8}','{9}')".format(
            onej, twoj, therej, xqname, name, hx, mj1, int(price), zflx, imgurl)
        print(sql)
        mysqlhe.insert(sql)
    else:
        print("已存在")

# for i in range(3,10):
#     url='http://sh.ganji.com/chuzu/pn{0}/'.format(i)
def shoyye(url):

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/49.0.2623.112 Safari/537.36'}
    html = requests.get(url, headers=headers)
    htmltxt = BeautifulSoup(html.text, "html.parser")
    # print(htmltxt)
    a = 0

    for ii in htmltxt.find_all("div", attrs={'class': 'f-list-item ershoufang-list'}):
        a = a + 1
        print(ii.find('a').get('href'))
        print('&&&&&&&&&&&&' ,)
        if ii.find('a').get('href').find('https://'):
            print(ii.find('a').get('href'))
            xq("https:" + ii.find('a').get('href'))
            print(a)
            # print("2@@@@@@@@@@@@@@@@@@@@@@")
        if a == 10:
            break
def deuser(request):
    name = request.session.get("name")
    teacheruser = Teacher.objects.filter(tname=name).first()
    id = request.GET['id']
    print(id)
    cxsql = "DELETE from teachers where id={0}".format(int(id))
    print(cxsql)

    mysqlhe.delete(cxsql)
    return HttpResponse('删除成功')
def rssz(request):
    id = request.GET['id']
    sql='update num set num={0}'.format(int(id))
    mysqlhe.update(sql)
    return HttpResponse('设置成功')
def lysc(request):
    id = request.GET['id']
    sql='delete from fk where id={0}'.format(int(id))
    mysqlhe.delete(sql)
    return HttpResponse('设置成功')